var path = require('path');


var mslibrary = require('ms-common-library');

var openjson = mslibrary.openjson;

var savejson = mslibrary.savejson;

var ArFor = mslibrary.ArFor;

var get_user_roles = function (id, config, callback) {
    var source = config.Source;
    new source("M_3", {
        user_id: id,
        id: 'home',
        "off": 0
    }, function (db) {
        if (db) {
            // getRoles(db.Table, list, callback)
            callback(db.Table);
        } else {
            callback(null);
        }
    });
}
module.exports = function (config) {
    var a = function (db, callback, off) {
        var filename = mslibrary.MD5(db.filename);
        var tempjsonfile = path.join(config.Files.Temp, "dbs/" + filename + ".json")
        openjson(tempjsonfile, function (error, json) {
            if (error || off) {
                get_user_roles(db.id, config, function (jurisdictions) {
                    var ajaxTest = {
                        error: 0,
                        name: db.name,
                        icon: db.icon,
                        jurisdictions: jurisdictions
                    };
                    if (jurisdictions && jurisdictions.length > 0) {
                        savejson(tempjsonfile, jurisdictions, function () {
                            callback(ajaxTest);
                        })
                    } else {
                        callback(ajaxTest);
                    }
                });
            } else {
                var ajaxTest = {
                    error: 0,
                    name: db.name,
                    icon: db.icon,
                    jurisdictions: json
                };
                callback(ajaxTest);
            }
        })
    };
    var source = config.Source;

    config.setParamet("InitJurisdictions", function (callback) {
        new source("M_4", {}, function (db) {
            db = (db && db.Table) ? db.Table : [];
            new ArFor(db, function () {
                callback()
            }).forEach(function (item, next) {
                config.setUserSource(item.id, item.Sources);
                a(item, function () {
                    next();
                }, true)
            })
        });
    })
    return a;
}